package com.lilingguo.anime.controller;

import com.lilingguo.anime.domain.FolderPo;
import com.lilingguo.anime.service.FolderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 文件路径
 *
 * @Author: GuoZi
 * @Date: 2021/05/30 22:14
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/s")
public class FolderController {

    FolderService folderService;

    /**
     * 将文件数据加载入库
     *
     * @return 加载结果
     */
    @GetMapping("/load")
    public String load() {
        int totalCount = folderService.findTotalCount();
        if (totalCount > 0) {
            return "no need to load";
        }
        boolean result = folderService.load();
        log.info("result = " + result);
        return "load over";
    }

    /**
     * 获取根目录下的文件
     *
     * @return 文件集合
     */
    @GetMapping(path = "/directoryList")
    public List<FolderPo> getList() {
        return folderService.findRootFolders();
    }

    /**
     * 根据文件id查询当前目录下的文件
     *
     * @param fid 文件id
     * @return 文件集合
     */
    @GetMapping(path = "/directoryList/{fid}")
    public List<FolderPo> getList(@PathVariable("fid") int fid) {
        return folderService.findChildFoldersById(fid);
    }

    /**
     * 根据文件id获取略缩图
     *
     * @param fid      文件id
     * @param response http响应对象
     */
    @GetMapping(path = "/thumbnail/{fid}", produces = "image/jpg")
    public void thumbnail(@PathVariable("fid") int fid, HttpServletResponse response) {
        String path = folderService.findThumbnailPath(fid);
        sendImage(path, response);
    }

    /**
     * 根据文件id获取图片
     *
     * @param fid      文件id
     * @param page     页数
     * @param response http响应对象
     */
    @RequestMapping("/image/{fid}/page/{page}")
    public void getImageList(@PathVariable("fid") int fid, @PathVariable("page") int page, HttpServletResponse response) {
        String path = folderService.findImagePath(fid, page);
        sendImage(path, response);
    }

    /**
     * 将文件传回前端
     *
     * @param path     文件路径
     * @param response http响应对象
     */
    private void sendImage(String path, HttpServletResponse response) {
        if (path == null) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[8192];
            int len;
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len);
            }
            bis.close();
            bos.close();
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }

}
